package com.zhang.novel.core.filter;

import com.zhang.novel.core.cache.CacheKey;
import com.zhang.novel.core.cache.CacheService;
import com.zhang.novel.core.utils.*;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class NovelFilter implements Filter {

    private String picSavePath;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 从配置类中获取图片保存路径
        picSavePath = filterConfig.getInitParameter("picSavePath");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        // 处理本地图片访问请求
        if (requestURI.contains(Constants.LOCAL_PIC_PREFIX)) {
            // 说明正在请求本地图片，将本地图片写出到页面
            // 设置图片过期时间
            response.setDateHeader("expires", System.currentTimeMillis() + 60 * 60 * 24 * 10 * 1000);
            // 获取字节输出流
            OutputStream out = response.getOutputStream();
            // 创建文件字节输入流
            InputStream input = new FileInputStream(new File(picSavePath + requestURI));
            byte[] bytes = new byte[4096];
            for (int len; (len = input.read(bytes)) != -1; ) {
                out.write(bytes,0 ,len);
            }
            input.close();
            out.close();
            return;
        }

        // 非本地图片访问请求处理
        String userMark = CookieUtil.getCookie(request, Constants.USER_CLIENT_MARK_KEY);
        if (null == userMark){
            userMark = UUIDUtil.getUUID32();
            CookieUtil.setCookie(response,Constants.USER_CLIENT_MARK_KEY,userMark);
        }

        ThreadLocalUtil.setCientId(userMark);
        // 根据浏览器类型选择前端模板
        String to = request.getParameter("to");
        CacheService cacheService = SpringUtil.getBean(CacheService.class);

        if("pc".equals(to)){
            cacheService.set(CacheKey.TEMPLATE_DIR_KEY+userMark,"",60*60*24);
        }else if("monile".equals(to)){
            cacheService.set(CacheKey.TEMPLATE_DIR_KEY+userMark,"mobile/",60*60*24);
        }else {
            // 自动识别是PC还是手机
            if(BrowserUtil.isMobile(request)){
                // 手机端
                ThreadLocalUtil.setTemplateDir("mobile/");
            }else {
                // pc端
                ThreadLocalUtil.setTemplateDir("");
            }

        }

        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
